package edu.whu.ioc;

import edu.whu.exception.MyException;
import edu.whu.object.BeanDefinition;
import edu.whu.readXML.XMLReader;
import edu.whu.readXML.impl.Dom4JReader;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MiniApplicationContext {
    private Map<String, Object> container = new HashMap<>();

    public MiniApplicationContext(String filepath) throws MyException {
        //获取根元素
        Element root = Dom4JReader.getRoot(Dom4JReader.loadFile(filepath));
        //获取所有的bean元素
        List<Element> beans = Dom4JReader.getBean(root);
        //将bean中的信息储存到beanDefinition
        List<BeanDefinition> beanDefinitionList = new ArrayList<>();
        try {
            for (Element e: beans) {
                BeanDefinition beanDefinition = BeanDefinition.class.newInstance();
                beanDefinition.load(e);
                beanDefinitionList.add(beanDefinition);
            }
        } catch(InstantiationException e) {
               throw new MyException(MyException.ErrorType.INSTANCE_ERROR,"创建bean对象失败");
        } catch (IllegalAccessException e) {
            throw new MyException(MyException.ErrorType.INSTANCE_ERROR,"创建bean对象失败");
        }
        //通过beanDefinition创建相应对象,并放到容器中
        for(BeanDefinition b : beanDefinitionList) {
            String id = b.getId();
            Object object = b.createObject(this);
            container.put(id,object);
        }
    }

    //获得bean实例
    public Object getBean(String id) {
        return container.get(id);
    }
}
